<template>
  <div class="user-page">
    <div class="user-page-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增用户
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="id" label="id" width="190" />
          <!-- <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-image
              :preview-teleported="true"
              style="width: 40px; height: 40px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template> -->
          <!-- </el-table-column> -->
          <el-table-column prop="userName" label="用户名" width="120">
            <template #default="scope">
              <div
                v-if="!scope.row.userName || scope.row.userName == 'NULL'"
              ></div>
              <div v-else>{{ scope.row.userName }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="openid" label="openId" width="270" /> -->
          <el-table-column prop="nickName" label="昵称" width="160" />
          <el-table-column prop="roleName" label="角色名" min-width="180">
            <template #default="scope">
              <div class="tag-field">
                <el-tag v-for="item in scope.row.roleList" :key="item.id">{{
                  item.name
                }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="phonenumber" label="手机号" width="120" />
          <el-table-column prop="createdAt" label="创建时间" width="210" />
          <el-table-column label="操作" fixed="right" min-width="220px">
            <template #default="scope">
              <!-- v-if="userPermission.editUserPerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="userPermission.removeUserPerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input
              placeholder="请输入用户名"
              v-model="addEditForm.userName"
              autocomplete="off"
              :disabled="addEditForm.disabled || addEditForm.id"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="addEditForm.password"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="角色" prop="roleIdList">
            <el-select
              v-model="addEditForm.roleIdList"
              placeholder="请选择角色"
              style="width: 100%"
              multiple
              :disabled="addEditForm.disabled"
            >
              <el-option
                v-for="option in roleList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input
              placeholder="请输入昵称"
              v-model="addEditForm.nickName"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input
              placeholder="请输入手机号"
              v-model="addEditForm.phonenumber"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!addEditForm.disabled">
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startAddRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除用户"
      width="400px"
    >
      <span>确定要删除当前用户？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getUserPagination,
  removeUser,
  updateUser,
  addUser,
  getAllRoleList,
} from "@/api/userManage.api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import { useUserPermission } from "@/utils/permission.utils";
const userPermission = useUserPermission();

const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

const searchForm = reactive({
  nickname: "",
  roleId: "",
});

const removeDialogVisible = ref(false);
const addDialogVisible = ref(false);
const addEditRef = ref<FormInstance>();
const addEditForm = reactive({
  id: null,
  password: "",
  nickName: "",
  phonenumber: "",
  userName: "",
  disabled: false,
  title: "",
  roleIdList: [],
});
const addEditRules = reactive({
  userName: [
    { required: true, message: "请输入11位手机号作为用户名", trigger: "blur" },
    {
      min: 11,
      max: 11,
      message: "请输入11位手机号作为用户名",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "请选择用户角色", trigger: "blur" }],
  password: [
    { required: true, message: "请输入6~30位密码", trigger: "blur" },
    { min: 6, max: 30, message: "请输入6~30位密码", trigger: "blur" },
  ],
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  phonenumber: [
    { required: true, message: "请输入11位手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "请输入11位手机号码", trigger: "blur" },
  ],
});

/***
 * 开始搜索
 */
const startSearch = () => {
  getDataList();
};

/***
 * 清空搜索条件
 */
const startClear = () => {
  searchForm.roleId = "";
  searchForm.userName = "";
  getDataList();
};

const showAddEditDialog = (item: any, type: number) => {
  //新增用户
  if (item.target) {
    addEditForm.id = null;
    addEditForm.userName = "";
    addEditForm.password = "";
    addEditForm.nickName = "";
    addEditForm.phonenumber = "";
    addEditForm.roleIdList = [];
    addEditForm.disabled = false;
    addEditForm.title = "新增用户";
    addDialogVisible.value = true;
    return;
  }

  addEditForm.id = item.id;
  addEditForm.userName = item.userName;
  addEditForm.password = item.password;
  addEditForm.nickName = item.nickName;
  addEditForm.phonenumber = item.phonenumber;
  addEditForm.roleIdList = item.roleIdList;
  //查看详情
  if (type === 1) {
    addEditForm.title = "查看详情";
    addEditForm.disabled = true;
    addDialogVisible.value = true;
    return;
  }

  //编辑
  addEditForm.title = "编辑用户";
  addEditForm.disabled = false;
  addDialogVisible.value = true;
};

const tableLoading = ref(false);
const tableData = ref([]);

const curSelectRow = ref("");
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startRemoveRole = () => {
  let id = curSelectRow.value?.id;
  removeUser([id])
    .then((res) => {
      console.log("success~~~~~");
      removeDialogVisible.value = false;
      ElMessage({
        message: "用户删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      ElMessage({
        message: err.msg || err,
        type: "error",
      });
    });
};

const startAddRole = () => {
  let formData = {
    userName: addEditForm.userName,
    password: addEditForm.password,
    nickName: addEditForm.nickName,
    phonenumber: addEditForm.phonenumber,
    roleIdList: addEditForm.roleIdList,
  };

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (addEditForm.id) {
        updateUser({
          ...formData,
          id: addEditForm.id,
        })
          .then((res) => {
            addDialogVisible.value = false;
            ElMessage({
              message: "用户修改成功",
              type: "success",
            });
            getDataList();
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: "error",
            });
          });
        return;
      }

      addUser(formData)
        .then((res) => {
          addDialogVisible.value = false;
          ElMessage({
            message: "用户新增成功",
            type: "success",
          });
          getDataList();
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};

const getDataList = () => {
  let searchCondition: {
    roleId?: string;
    nickname?: string;
  } = {};
  if (searchForm.roleId) {
    searchCondition.roleId = searchForm.roleId;
  }
  if (searchForm.nickname) {
    searchCondition.nickname = searchForm.nickname;
  }

  tableLoading.value = true;
  getUserPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false;
      console.log(res);
      tableData.value = res.list || [];
      formData.total = Number(res.total);
    })
    .catch((error) => {
      console.log(error);
      tableLoading.value = false;
    });
};

const roleList = ref([]);
const startGetAllRoleList = () => {
  getAllRoleList({}).then(function (res: any) {
    console.log("startGetAllRoleList: ", res);
    roleList.value = res;
  });
};

onMounted(() => {
  getDataList();
  startGetAllRoleList();
});
</script>
<style lang="scss" scoped>
.user-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.user-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
